package com.jiuyuejiu.singleimg;

import android.content.ClipboardManager;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jiuyuejiu.R;
import com.jiuyuejiu.application.ConstValues;
import com.jiuyuejiu.base.BaseActivity;
import com.jiuyuejiu.func_video.VideoService;
import com.jiuyuejiu.func_video.domain.VideoDetailStc;
import com.jiuyuejiu.func_video.domain.VideoFenleiStc;
import com.jiuyuejiu.func_video.videosync.VideoSyncActivity;
import com.jiuyuejiu.utils.ShanHaiUtil;
import com.jiuyuejiu.utils.ViewUtil;
import com.kylin.core.loader.LatteLoader;
import com.kylin.core.utils.dbtutil.FileUtil;
import com.kylin.core.utils.dbtutil.FunUtil;
import com.kylin.core.utils.dbtutil.PrefUtils;
import com.kylin.core.utils.flyn.Eyes;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Random;

import androidx.annotation.Nullable;
import cn.jzvd.Jzvd;


/**
 * 获取随机数 Activity
 */
public class HtmlVideoActivity extends BaseActivity implements View.OnClickListener {


    private ImageView img;

    MyHandler handler;
    private VideoService service;


    private int videocount = 12;


    private Random rand;

    private ClipboardManager myClipboard;// 剪贴板

    // 视频播放控制器
    SensorManager sensorManager;
    Jzvd.JZAutoFullscreenListener sensorEventListener;

    private String categoryname;
    private String imgurl;

    // 文件的MD5名称
    private String fileName;

    private ArrayList<VideoFenleiStc> videoFenleiStcs;

    /**
     * 接收子线程消息的 Handler
     */
    public static class MyHandler extends Handler {

        // 软引用
        SoftReference<HtmlVideoActivity> fragmentRef;

        public MyHandler(HtmlVideoActivity fragment) {
            fragmentRef = new SoftReference<HtmlVideoActivity>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            HtmlVideoActivity fragment = fragmentRef.get();
            if (fragment == null) {
                return;
            }
            Bundle bundle = msg.getData();

            // 处理UI 变化
            switch (msg.what) {
                case ConstValues.WAIT1:// // 获取分类列表的回调
                    fragment.getJsonSuc(bundle);
                    break;
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_img_detail);

        // 标题栏白底黑字
        Eyes.setStatusBarLightMode(this, Color.WHITE);

        initView();
        initData();

    }

    private void initView() {
        img = (ImageView) findViewById(R.id.imagedetail_img_show);
    }

    private void initData() {
        handler = new MyHandler(this);
        service = new VideoService(HtmlVideoActivity.this, handler);


        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);// CLIPBOARD_SERVICE



        rand = new Random();


        // 视频播放控制器
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new Jzvd.JZAutoFullscreenListener();


        // 获取上一页传递过来的数据
        Intent i = getIntent();
        categoryname = i.getStringExtra("categoryname");
        imgurl = i.getStringExtra("imgurl");

        Glide.with(HtmlVideoActivity.this)
                .load(imgurl)
                .thumbnail(Glide.with(HtmlVideoActivity.this).load(R.drawable.gif_loading))// 缩略图
                .centerCrop()// 按比例放大/缩小,铺满整个ImageView控件
                .into(img);

        // 下载所有分类
        downloadVideoCatList();
    }

    // ----↓ 下载所有分类 2022/6/4 10:45 ↓------------------------------------------------------------------------------------
    private void downloadVideoCatList() {
        if (hasPermission(ConstValues.WRITE_READ_EXTERNAL_PERMISSION)) {
            // 拥有了此权限,那么直接执行业务逻辑
            // 先下载所有分类
            downloadVideoCatJson();
        } else {
            // 还没有对一个权限(请求码,权限数组)这两个参数都事先定义好
            requestPermission(ConstValues.WRITE_READ_EXTERNAL_CODE, ConstValues.WRITE_READ_EXTERNAL_PERMISSION);
        }
    }

    // 手动拥有读写权限后 执行下载文件
    @Override
    public void doWriteSDCard() {
        try {
            // 拥有了此权限,那么直接执行业务逻辑
            // 先下载所有分类
            downloadVideoCatJson();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 先下载所有分类
    private void downloadVideoCatJson() {

        // 获取所有分类
        fileName = FunUtil.StringToMd5(ConstValues.LANDKING + categoryname);
        FileUtil.deleteFile(new File(ShanHaiUtil.parseFilePath(fileName)));// 先删除
        // String downurl = ShanHaiUtil.getHttpid() + ConstValues.JIEQUPATH + ConstValues.TXTNAME;
        String downurl = ShanHaiUtil.getHttpid() + ConstValues.LANDKING + "/" + categoryname + "/" + ConstValues.TXTNAME;


        // 请求
        service.downCatVideoJsonList(downurl,// 请求url
                fileName, // 本地存储名称
                true, // 是否显示进度条 false不显示下载进度,true显示下载进度框
                ConstValues.WAIT1);// 用于当前Activity界面handle的对应回调接收 比如what1,what2
    }

    // ----↑ 载所有分类 2022/6/4 10:45 ↑------------------------------------------------------------------------------------

    // ----↓ 下载所有分类的回调 2021/12/19 13:33 ↓------------------------------------------------------------------------------------
    private void getJsonSuc(Bundle bundle) {

        String formjson = bundle.getString("formjson");
        String status = bundle.getString("status");

        if (ConstValues.SUCCESS.equals(status)) {
            String filepath = ShanHaiUtil.parseFilePath(fileName);// 拼接文件路径
            File file = new File(filepath);
            if (file.exists()) {//存在本地;
                try {
                    // 传入File文件 读取文件内容
                    String result = ShanHaiUtil.parseFileToString(file);
                    // 传入字符串 将字符串分割成数组
                    String[] read = ShanHaiUtil.splitStringToArray(result);
                    // 将数组 转成 集合
                    videoFenleiStcs = ShanHaiUtil.parseStringArrayToList(read);


                    if (videoFenleiStcs != null && videoFenleiStcs.size() > 0) {

                        // 1 是否重新请求每个分类的视频列表 默认true true需要重新下载  false不需要重新下载
                        boolean isgetvideourl = PrefUtils.getBoolean(HtmlVideoActivity.this, ConstValues.ISGETVIDEOURL, true);

                        // 2 第一个分类文件 本地是否有这个文件
                        VideoFenleiStc videoFenleiStc = videoFenleiStcs.get(1);
                        String fileName = FunUtil.StringToMd5(categoryname + videoFenleiStc.getCategory());// 分类名称转MD5
                        String pdfpath = ShanHaiUtil.parseFilePath(fileName);// 拼接文件路径
                        File docFile = new File(pdfpath);

                        if (isgetvideourl || !docFile.exists()) {// 下载每个分类的视频列表 下载每个_LIST文件

                            // 下载每个分类文件
                            downFileJsonByPath();

                        } else {// 随机读取 10条视频记录
                            readRandomVideoRecord();
                        }


                    } else {
                        Toast.makeText(HtmlVideoActivity.this, "获取分类列表失败", Toast.LENGTH_SHORT).show();
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(HtmlVideoActivity.this, "没有找到视频文件", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(HtmlVideoActivity.this, "没有找到分类文件", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(HtmlVideoActivity.this, formjson, Toast.LENGTH_SHORT).show();
        }
    }
    // ----↑ 下载所有分类的回调 2021/12/19 13:33 ↑------------------------------------------------------------------------------------


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1011:
                String result = data.getExtras().getString("result");//得到新Activity 关闭后返回的数据
                Toast.makeText(HtmlVideoActivity.this, result, Toast.LENGTH_SHORT).show();
                // 随机读取 10条视频记录
                readRandomVideoRecord();
        }
    }


    private void readRandomVideoRecord() {

        // 读取所有视频记录
        if (videoFenleiStcs != null && videoFenleiStcs.size() > 0) {
            // 将所有的记录打印出来
            StringBuffer buffer = new StringBuffer();

            // 制造锚点  <a name="backtop">Hao123</a>
            buffer.append("<a name=\"backtop\"></a>\n\n");
            buffer.append("<h3>Hao123</h3>\n\n");

            for (int i = 0; i < videoFenleiStcs.size(); i++) {
                VideoFenleiStc videoFenleiStc = videoFenleiStcs.get(i);

                // 跳到锚点  <a name="#1000">00 御姐少妇篇</href>
                buffer.append("<a href=\"#");
                buffer.append(( 1000 + i )+"");
                buffer.append("\">");
                // buffer.append(videoFenleiStc.getCategory());
                buffer.append(singleBackDouble(i+1)+" "+videoFenleiStc.getCategory().substring(2,8));// 跳到锚点  // 序号+名字截取
                buffer.append("</a>");
                buffer.append("  ");


                // 换行
                if (i == 4 || i == 9 || i == 14 || i == 19 || i == 24 || i == 29 || i == 34 || i == 39 || i == 44 ) {
                    buffer.append("\n");
                }
            }
            buffer.append("\n");
            buffer.append("\n");


            for (int i = 0; i < videoFenleiStcs.size(); i++) {
                VideoFenleiStc videoFenleiStc = videoFenleiStcs.get(i);

                // 制造锚点  #### <a name="1000"> 00 御姐少妇篇 </a>
                buffer.append("<a name=\"");
                buffer.append(( 1000 + i )+"");// 制造锚点
                buffer.append("\"></a>\n\n");

                buffer.append("<h3>");
                // buffer.append(videoFenleiStc.getCategory());
                buffer.append(singleBackDouble(i+1)+" "+videoFenleiStc.getCategory().substring(2,8));// 跳到锚点  // 序号+名字截取
                buffer.append("</h3>\n\n");

                // String fileName = FunUtil.StringToMd5(videoFenleiStc.getCategory());
                String fileName = FunUtil.StringToMd5(categoryname + videoFenleiStc.getCategory());// 分类名称转MD5
                // 拼接文件路径
                String pdfpath = ShanHaiUtil.parseFilePath(fileName);
                File docFile = new File(pdfpath);
                if (docFile.exists()) {//存在本地;
                    try {
                        // 传入File文件 读取文件内容
                        String result = ShanHaiUtil.parseFileToString(docFile);
                        // 传入字符串 将字符串分割成数组
                        String[] read = ShanHaiUtil.splitStringToArray(result);
                        // 将数组 转成 集合
                        ArrayList<VideoDetailStc> videoDetailStcs = ShanHaiUtil.getVideoListByVideoArray(videoFenleiStc.getCategory(),
                                ConstValues.LANDKING + "/" + categoryname + "/", read);

                        for (int j = 0; j < videoDetailStcs.size(); j++) {
                            VideoDetailStc videoDetailStc = videoDetailStcs.get(j);
                            // <a href="http://192.168.31.128:8080/landking/video/01 夫前目犯篇/JUL-085 從知道妻子外遇，直到在我面前做愛的出軌記錄影像―01.mp4">JUL-085 從知道妻子外遇，直到在我面前做愛的出軌記錄影像―01.mp4</a>
                            buffer.append("<a href=\"");
                            buffer.append(videoDetailStc.getVideourl());
                            buffer.append("\">");
                            buffer.append((j+1)+" "+videoDetailStc.getVideoname());
                            buffer.append("</a>\n\n");
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(HtmlVideoActivity.this, "没有找到指定文件", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(HtmlVideoActivity.this, "没有找到指定文件", Toast.LENGTH_SHORT).show();
                }

                // 跳到锚点
                buffer.append("<h5><a href=\"#backtop\">回到顶部</a></h5>\n\n");
            }


            try {
                String res = buffer.toString();
                // /storage/emulated/0/AiMee/Android/data/localpath
                String path = FileUtil.getSDPath() + File.separator + ConstValues.LOCALPATH;
                writeFile("html", path, res);
                Toast.makeText(HtmlVideoActivity.this, "生成文件成功", Toast.LENGTH_SHORT).show();
                HtmlVideoActivity.this.finish();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        LatteLoader.stopLoading();
    }


    // 数字不足位数前面补0
    private String singleBackDouble(int que){
        //如果数字1是整型,如下处理：
        DecimalFormat decimalFormat =new DecimalFormat("00");
        String string2=decimalFormat.format(que);
        return string2;
    }


    public static void writeFile(String FileName, String dirsPath, String content) throws IOException {
        File dirs = new File(dirsPath);
        File file = new File(dirsPath + "/" + FileName + ".txt");
        //如果文件夹不存在就创建文件夹
        if (!dirs.exists()) {
            dirs.mkdirs();
        }
        //如果文件不存在就创建文件
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write(content);
        fileWriter.close();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_navigation_rl_back:// 返回
                this.finish();
                break;
            case R.id.top_navigation_rl_confirm://
                if (ViewUtil.isDoubleClick(v.getId(), 2500))
                    return;

                // 下载每个分类文件
                downFileJsonByPath();

                break;
        }
    }

    // 下载每个分类文件
    public void downFileJsonByPath() {
        Intent intent = new Intent(HtmlVideoActivity.this, VideoSyncActivity.class);
        intent.putExtra("categoryname", categoryname);  // 下载路径
        intent.putExtra("videoFenleiStcs", videoFenleiStcs);  // 保存本地文件名称 _LIST.TXT
        startActivityForResult(intent, 1011);
    }

    @Override
    public void onBackPressedSupport() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressedSupport();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        Jzvd.releaseAllVideos();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
